#include "SDLWrapper.h"
#include <iostream>

SDLWrapper::SDLWrapper(std::string screenTitle, int widthResolution,
		int heightResolution, int bitsPerPixel, Color bgrColor) {

	//Attach the game name to the screenTitle
	this->screenTitle = GAME_TITLE + screenTitle;
	this->widthResolution = widthResolution;
	this->heightResolution = heightResolution;
	this->bitsPerPixel = bitsPerPixel;
	this->playerName = STRING_EMPTY;
	this->bgrColor = bgrColor;

}

SDLWrapper::~SDLWrapper() {
	delete (this->screen);
	SDL_Quit();
}

int SDLWrapper::pullEvent(Event** event) {
	SDL_Event sdlEvent;
	int ret = SDL_PollEvent(&sdlEvent);
	if (ret) {
		//Delete previous reference if exists
		if (*event != NULL)
			delete *event;

		*event = new Event(sdlEvent);
	}
	return ret;
}

bool SDLWrapper::start() {
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
		return false;
	}

	SDL_EnableUNICODE( SDL_ENABLE);

	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

	screen = new Surface();
	screen->SetVideoMode(this->widthResolution, this->heightResolution,
			this->bitsPerPixel, SDL_SWSURFACE);

	if (screen == NULL) {
		return false;
	}
	if (TTF_Init() == -1) {
		return false;
	}

	int aux = Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096);
	if (aux == -1) {
		return false;
	}

	SDL_WM_SetCaption(screenTitle.c_str(), NULL);

	return true;
}

void SDLWrapper::stop() {
	Mix_CloseAudio();
	TTF_Quit();

}

void SDLWrapper::setPlayerName(std::string playerName) {
	this->playerName = playerName;
	std::stringstream ss;
	ss << "PlayerName: " << playerName;
	Logger::debug("SDLWrapper", "setPlayerName", &ss);
}

void SDLWrapper::clearScreen() {
	SDL_FillRect(screen->getSurface(), &screen->getSurface()->clip_rect,
			bgrColor.getColor());
}

void SDLWrapper::refreshScreen() {
	if (SDL_Flip(this->screen->getSurface()) != 0) {
		Logger::debug("SDLWrapper", "refreshScreen",
				"no se pudo refrescar la pantalla");
	}
}

void SDLWrapper::updateVideoMode(int w, int h, Color bgrColor) {
	this->screen->SetVideoMode(w, h, BITS_PER_PIXEL, SDL_SWSURFACE
			| SDL_RESIZABLE);
	this->widthResolution = w;
	this->heightResolution = h;
	this->bgrColor = bgrColor;

	SDL_WM_SetCaption(screenTitle.c_str(), NULL);

	SDL_FillRect(screen->getSurface(), &screen->getSurface()->clip_rect,
			this->bgrColor.getColor());
}

Surface* SDLWrapper::getMainSurface() {
	return this->screen;
}

void SDLWrapper::changeScreenTitle(std::string screenTitle) {
	this->screenTitle = screenTitle;
}
